<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Users_model extends CI_Model {

    function users_login_validation($data) {
        $params = array(
            'username' => $data['username'],
            'password' => do_hash($data['password']),
        );
        $query = $this->db->get_where('users', $params);
        $row = $query->row();
		if(!empty($row)){
			if ($data['username'] == $row->username && do_hash($data['password']) == $row->password) {
				$row->logged_in = TRUE;
				$userdata = (array) $row;
				$this->db->where('user_id', $row->user_id);
				$this->db->update('users', $userdata);
				$this->session->set_userdata($userdata);
				return TRUE;
			}
		}
        return FALSE;
    }

    function users_process_logout() {
        $updated = FALSE;
        $user_id = $this->users_lib->get_user_id();
        $this->db->where('user_id', $user_id);
        $new_value = array('logged_in' => 1);
        $updated = $this->db->update('users', $new_value);
        if ($updated) {
            $this->session->sess_destroy();
            return TRUE;
        }
        return FALSE;
    }

    function users_register($data) {

        $insert_user = FALSE;
        $insert_profile = FALSE;

        $usersdata = array(
            'username' => $data['email'],
            'password' => do_hash($data['password']),
            'email' => $data['email'],
            'logged_in' => 0
        );

        $insert_user = $this->db->insert('users', $usersdata) ? TRUE : FALSE;

        $userid = $this->db->insert_id();

        if ($insert_user) {
            $profile_data = array(
                'user_id' => $userid,
                'firstname' => $data['firstname'],
                'lastname' => $data['lastname'],
                'sex' => $data['sex'],
            );

            $insert_profile = $this->db->insert('users_profile', $profile_data) ? TRUE : FALSE;
        }

        if ($insert_user && $insert_profile) {

            $usersdata['logged_in'] = 1;

            if ($this->users_lib->is_login()) {

                $this->db->where('user_id', $userid);
                $this->db->set('logged_in', 1);
                $this->db->update('users');

                $this->session->set_userdata($usersdata);
            }
        }
        return $this->users_lib->is_login() && $insert_profile && $insert_user;
    }

    function users_check_unique_mail($mail) {

        $this->db->select('email');
        $this->db->from('users');
        $this->db->where('email', 'email');

        $result = $this->db->get()->row();

        return empty($result) ? TRUE : FALSE;
    }

    function users_get_profile($params=array()){
        $output=$this->db->get_where('users_profile',$params)->row();
        return $output;
    }

}
